package com.rzjm.exercise.common.generator;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 年月日流水ID生成器, 采用前缀+时间+原子数的形式实现
 * 建议相同的配置采用同一个实例
 */
public class SerialIdGenerator {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
    private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    public String next() {
        lock.readLock().lock();
        StringBuffer sb = new StringBuffer(LocalDateTime.now().format(FORMATTER)).append(new AtomicInteger(1).getAndIncrement());
        lock.readLock().unlock();
        return sb.toString();
    }
}
